<template>
  <div class="page_content" style="background: #fcfcfc;">
    <header>
      <van-nav-bar class="main_header" :title="title" />
    </header>
    <div class="main_content" style="bottom: 50px;">
      <template v-if="gameInfo.id">
        <!-- 赛事头部 -->
        <div class="game_content">
          <van-loading v-if="gameLoading" class="gl_loading" vertical />
          <div v-if="gameInfo.backgroundImage" class="game_bg" :style="'background:' + handleBackgroundImg(gameInfo.backgroundImage)" />
          <div class="game_message_logo gl_clear">
            <div class="left_logo">
              <img :src="getStaticFileUrl(gameInfo.logoImage)" alt="">
            </div>
            <div class="right_content">
              <div class="game_name">{{ gameInfo.name }}</div>
              <div class="game_item gl_mt_10">
                开赛时间：{{ gameInfo.startTime && gameInfo.startTime.substring(0, 10) }} - {{ gameInfo.endTime && gameInfo.endTime.substring(0, 10) }}
              </div>
              <div class="game_item gl_mb_10">
                <span v-show="statistics.isolateCompetitionCount">{{ statistics.isolateCompetitionCount }}场赛事；</span>
                <span v-show="statistics.isolateCompetitionCount">{{ statistics.delegationCount }}个参赛单位；</span>
                <span v-show="statistics.isolateCompetitionCount">{{ statistics.athleteCategoryCount }}人次</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 报名 -->
        <div class="game_entry">
          <van-button
            type="info"
            class="game_entry_btn"
            size="small"
            color="#0C5ECD"
            @click="clickEntry"
          >
            申办分站赛
          </van-button>
        </div>

        <!-- 首页TAB -->
        <van-tabs v-model="active">
          <van-tab title="首页">
            <!-- 赛事信息 -->
            <div class="game_message">
              <div class="model_title">赛事信息</div>
              <div class="game_message_content model_content">
                <div class="game_item">赛事等级：{{ gameInfo.level && gameInfo.level.name }}</div>
                <!-- <div class="game_item">比赛地址：{{ gameInfo.address }}</div> -->
                <div class="game_item">联系方式：{{ gameInfo.contactPhoneNumber }}</div>
                <div v-if="gameInfo.entryNotice || gameInfo.disclaimerNotice || gameInfo.regulation" class="game_item">
                  赛事相关条例：
                  <!-- <a v-if="gameInfo.entryNotice" class="download_file" @click="downloadFile(gameInfo.entryNotice, '报名须知')">《报名须知》</a>
                  <a v-if="gameInfo.disclaimerNotice" class="download_file" @click="downloadFile(gameInfo.disclaimerNotice, '免责声明')">《免责声明》</a>
                  <a v-if="gameInfo.regulation" class="download_file" @click="downloadFile(gameInfo.regulation, '竞赛规程')">《竞赛规程》</a> -->
                  <a v-if="gameInfo.entryNotice" target="_blank" :href="fileUrl + gameInfo.entryNotice" class="download_file">《报名须知》</a>
                  <a v-if="gameInfo.disclaimerNotice" target="_blank" :href="fileUrl + gameInfo.disclaimerNotice" class="download_file">《免责声明》</a>
                  <a v-if="gameInfo.regulation" target="_blank" :href="fileUrl + gameInfo.regulation" class="download_file">《竞赛规程》</a>
                </div>
              </div>
            </div>
            <!-- 赛事架构（组委会） -->
            <committee-info ref="committeeInfo" :game-id="gameId" />
            <substation ref="substation" :game-info="gameInfo" />
            <integral ref="integral" :game-info="gameInfo" @jumpToScoreList="jumpToScoreList" />
            <delegation ref="delegation" :game-info="gameInfo" @jumpToDelegationList="jumpToDelegationList" />
          </van-tab>
          <van-tab title="分站赛">
            <tabSubstation :game-info="gameInfo" />
          </van-tab>
          <van-tab title="参赛机构">
            <tabMechanism :game-info="gameInfo" />
          </van-tab>
          <van-tab title="参赛选手">
            <tabPlayer :game-info="gameInfo" :statistics="statistics" />
          </van-tab>
          <van-tab title="教练领队榜">
            <tabOfficial :game-info="gameInfo" />
          </van-tab>
          <van-tab title="区域榜">
            <tabArea :game-info="gameInfo" />
          </van-tab>
          <van-tab title="赛区榜">
            <tabDelegation :game-info="gameInfo" />
          </van-tab>
          <!-- <van-tab title="榜单排名">
            <tabList :list-active="listActive" :game-info="gameInfo" />
          </van-tab> -->
        </van-tabs>

      </template>
      <template v-else>
        <van-empty description="暂无数据" />
      </template>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { getToken } from '@/lib/auth';
import {
  api_GET_EventsManagementCompetitionWithRoute,
  api_GET_EventsManagementCompetitionRequestCompetitionLeagueIndexDataLeagueCompetitionId // 联赛下数据管理-联赛数据统计(联赛首页)
} from '@/extend/api/gameswaggerApi/app';

import committeeInfo from '../components/committeeInfo';
import substation from '../components/substation';
import integral from '../components/integral';
import delegation from '../components/delegation';

import tabSubstation from './substation.vue';
import tabPlayer from './player.vue';
// import tabList from './list.vue';
import tabMechanism from './mechanism.vue';
import tabOfficial from './official.vue';
import tabArea from './area.vue';
import tabDelegation from './delegation.vue';

export default {
  name: 'GameHome',
  components: {
    committeeInfo,
    substation,
    integral,
    delegation,
    tabSubstation,
    tabPlayer,
    // tabList,
    tabMechanism,
    tabOfficial,
    tabArea,
    tabDelegation
  },
  data() {
    return {
      active: 0,
      listActive: 0,
      baseUrl: `${WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE}`,
      fileUrl: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}`,
      tokenInfo: getToken(),
      gameLoading: false,
      title: '赛事',
      gameInfo: {},
      gameId: '',
      leagueTab: [],
      statistics: {}
    };
  },
  computed: {
    gameInfoStatusCode () {
      const _gameInfo = this.gameInfo.status || {};
      return _gameInfo.code;
    }
  },
  created() {
    const $route = this.$route;
    const _paramsId = $route.params.id;
    this.gameRoute = _paramsId.split('_')[0];
// 因为短域名原因手动添加VUE_APP_Get_TenantId
    this.tenantId =  process.env.VUE_APP_Get_TenantId;
    this.getGameInfo();
  },
  methods: {
    // 获取赛事详情
    getGameInfo() {
      const gameQO = {};
      gameQO.route = this.gameRoute;
      gameQO.IncludeStatus = true;
      gameQO.IncludeType = true;
      gameQO.IncludeApproveStatus = true;
      gameQO.IncludeApproveStatus = true;
      gameQO.IncludeLevel = true;
      gameQO.IncludeSetting = true;
      gameQO.IncludeReportSetting = true;
      gameQO.IncludeEntryFields = true;
      gameQO.IncludeParent = true;
      this.getGameInfoByGameRoute(gameQO);
    },
    // 根据赛事路由获取赛事信息
    getGameInfoByGameRoute(gameQO) {
      this.gameLoading = true;
      api_GET_EventsManagementCompetitionWithRoute(gameQO).then(res => {
        this.gameLoading = false;
        this.gameInfo = res || {};
        this.title = this.gameInfo.name || this.title;
        this.gameId = this.gameInfo.id;
        this.getPlayerStatistics(this.gameInfo.id);
      }, () => {
        this.gameLoading = false;
        this.$toast.fail('获取赛事详情失败！');
      });
    },
    // 处理背景图
    handleBackgroundImg(relatvieUrl) {
      return `url('${this.getStaticFileUrl(relatvieUrl)}') center no-repeat;background-size: cover;`;
    },
    jumpToDelegationList () {
      this.active = 3;
      this.listActive = 0;
    },
    jumpToScoreList () {
      this.active = 3;
      this.listActive = 3;
    },
    // 点击报名
    clickEntry() {
      this.$router.push({
        name: 'SubstationList',
        params: {
          gameRoute: this.gameRoute
        }
      });
    },
    // 获取运动员统计
    getPlayerStatistics(id) {
      api_GET_EventsManagementCompetitionRequestCompetitionLeagueIndexDataLeagueCompetitionId(id)
        .then(
          res => {
            this.statistics = res;
            console.log(res);
          }
        );
    },
    // 获取文件地址
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    checkBrowser () {
      const ua = window.navigator.userAgent;
      if (ua.indexOf('MicroMessenger') !== -1) {
        return false;
      }
      return true;
    },
    downloadFile(fileUrl, fileName) {
      const _isSupportBrower = this.checkBrowser();
      if (!_isSupportBrower) {
        this.$toast('很抱歉，微信浏览器暂不支持此文件下载，请移至默认浏览器打开。');
        return;
      }
      console.log(Download);
      axios({
        methods: 'get',
        url: `${this.fileUrl}${fileUrl}`,
        responseType: 'blob'
      }).then(res => {
        var blob = new Blob([res.data]);
        const suffix = fileUrl.split('.')[fileUrl.split('.').length - 1];
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, fileName + '.' + suffix);
          return;
        }
        const downloadElement = document.createElement('a');
        const href = window.URL.createObjectURL(res.data);
        downloadElement.style.display = 'none';
        downloadElement.href = href;
        // downloadElement.download = fileName + '.' + suffix;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      }).catch(error => {
        console.dir(error);
        this.$toast(String(error));
      });
    }
  }
};
</script>

<style>
/* vant-ui */
.van-tab .van-tab__text {
  color: #969799;
  font-weight: 500;

}
.van-tab.van-tab--active .van-tab__text {
  color: #AB3131;
}
.van-tabs__line {
  border-radius: 2px;
  background-color: #AB3131;
}

/*  */
.main_content .game_content {
  position: relative;
}
.main_content .game_content .game_bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #fff;
  background-repeat: no-repeat;
  background-size: cover;
  z-index: -1;
}
.main_content .game_content .game_message_logo {
  color: #eee;
  padding: 10px 20px;
  box-sizing: border-box;
}
.main_content .game_content .left_logo {
  float: left;
  width: 66px;
  height: 66px;
}
.main_content .game_content .left_logo img {
  width: 66px;
  height: 66px;
  vertical-align: middle;
}
.main_content .game_content .right_content {
  float: left;
  width: calc(100% - 87px);
  margin-left: 21px;
  background: #ffffff;
  border-radius: 3px;
  box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.10);
  box-sizing: border-box;
}
.main_content .game_content .right_content .game_name {
  position: relative;
  font-size: 14px;
  line-height: 18px;
  /* min-height: 53px; */
  padding: 10px 26px 7px 11px;
  font-weight: bold;
  color: #333333;
  box-sizing: border-box;
  /* border-bottom: 1px solid #d1d1d1; */
}
.main_content .game_content .right_content .game_name::after {
  display: block;
  content: "";
  position: absolute;
  width: 95%;
  height: 1px;
  background-color: #D1D1D1;
  left: 2.5%;
  bottom: 0;
}
.main_content .game_content .right_content .game_item {
  font-size: 12px;
  line-height: 18px;
  color: #666666;
  margin-top: 5px;
  padding: 0 10px;
  box-sizing: border-box;
}
.main_content .game_entry {
  width: 100%;
  background: #fff;
  padding: 0 20px;
}
.main_content .game_entry .game_entry_btn {
  width: 100%;
  height: 40px;
  border-radius: 5px;
}
.main_content .model_title {
  padding: 15px 26px 10px;
  font-size: 16px;
  line-height: 23px;
  font-weight: bold;
  color: #333;
}
.main_content .model_content {
  width: calc(100% - 20px);
  margin: 0 auto;
  background: #fff;
  border-radius: 3px;
  box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.10);
}
.main_content .game_message_content {
  padding: 10px 16px;
}
.main_content .game_message_content .game_item {
  font-size: 14px;
  line-height: 18px;
  color: #666666;
  margin-top: 5px;
  box-sizing: border-box;
}
.main_content .game_message_content .download_file {
  color: #DC1D1D;
}
</style>
